import { makeAutoObservable } from 'mobx';
import { inject, injectable } from 'inversify';
import { AuthRepository } from '../data/auth.repository.ts';
import { UserModel } from '../../user/models/user.model.ts';
import { APIClient } from '@todo/core';

@injectable()
export class AuthInitUseCase {
  constructor(
    @inject(AuthRepository)
    private authRepository: AuthRepository,
    @inject(UserModel)
    private userModel: UserModel,
    @inject(APIClient)
    private apiClient: APIClient,
  ) {
    makeAutoObservable(this);
  }

  async execute(cb: () => void): Promise<void> {
    try {
      const result = await this.authRepository.refresh();

      if (result.data) {
        this.apiClient.setAuthTokens(
          result.data.accessToken,
          result.data.refreshToken,
          result.data.expiresIn,
          true,
        );
      }
      this.userModel.authenticated = true;
      this.apiClient.setLogoutCallback(cb);
    } catch (e) {
      this.userModel.authenticated = false;
    }
  }
}
